// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#include <pollux/functions/lib/aggregates/set_base_aggregate.h>

namespace kumo::pollux::functions::aggregate::sparksql {
    namespace {
        // Null inputs are excluded by setting 'ignoreNulls' as true.
        // Empty arrays are returned for empty groups by setting 'nullForEmpty'
        // as false.
        template<typename T>
        using SparkSetAggAggregate = SetAggAggregate<T, true, false>;

        // NaN inputs are treated as distinct values.
        template<typename T>
        using FloatSetAggAggregateNaNUnaware = SetAggAggregate<
            T,
            true,
            false,
            pollux::aggregate::prestosql::FloatSetAccumulatorNaNUnaware<T> >;
    } // namespace

    void registerCollectSetAggAggregate(
        const std::string &prefix,
        bool withCompanionFunctions,
        bool overwrite) {
        std::vector<std::shared_ptr<exec::AggregateFunctionSignature> > signatures = {
            exec::AggregateFunctionSignatureBuilder()
            .typeVariable("T")
            .returnType("array(T)")
            .intermediateType("array(T)")
            .argumentType("T")
            .build()
        };

        auto name = prefix + "collect_set";
        exec::registerAggregateFunction(
            name,
            std::move(signatures),
            [name](
        core::AggregationNode::Step step,
        const std::vector<TypePtr> &argTypes,
        const TypePtr &resultType,
        const core::QueryConfig & /*config*/)
        -> std::unique_ptr<exec::Aggregate> {
                POLLUX_CHECK_EQ(argTypes.size(), 1);

                const bool isRawInput = exec::isRawInput(step);
                const TypePtr &inputType =
                        isRawInput ? argTypes[0] : argTypes[0]->childAt(0);
                const TypeKind typeKind = inputType->kind();

                switch (typeKind) {
                    case TypeKind::BOOLEAN:
                        return std::make_unique<SparkSetAggAggregate<bool> >(resultType);
                    case TypeKind::TINYINT:
                        return std::make_unique<SparkSetAggAggregate<int8_t> >(resultType);
                    case TypeKind::SMALLINT:
                        return std::make_unique<SparkSetAggAggregate<int16_t> >(resultType);
                    case TypeKind::INTEGER:
                        return std::make_unique<SparkSetAggAggregate<int32_t> >(resultType);
                    case TypeKind::BIGINT:
                        return std::make_unique<SparkSetAggAggregate<int64_t> >(resultType);
                    case TypeKind::HUGEINT:
                        POLLUX_CHECK(
                            inputType->isLongDecimal(),
                            "Non-decimal use of HUGEINT is not supported");
                        return std::make_unique<SparkSetAggAggregate<int128_t> >(resultType);
                    case TypeKind::REAL:
                        return std::make_unique<FloatSetAggAggregateNaNUnaware<float> >(
                            resultType);
                    case TypeKind::DOUBLE:
                        return std::make_unique<FloatSetAggAggregateNaNUnaware<double> >(
                            resultType);
                    case TypeKind::TIMESTAMP:
                        return std::make_unique<SparkSetAggAggregate<Timestamp> >(
                            resultType);
                    case TypeKind::VARBINARY:
                        [[fallthrough]];
                    case TypeKind::VARCHAR:
                        return std::make_unique<SparkSetAggAggregate<StringView> >(
                            resultType);
                    case TypeKind::ARRAY:
                        [[fallthrough]];
                    case TypeKind::ROW:
                        return std::make_unique<SparkSetAggAggregate<ComplexType> >(
                            resultType);
                    case TypeKind::UNKNOWN:
                        return std::make_unique<SparkSetAggAggregate<UnknownValue> >(
                            resultType);
                    default:
                        POLLUX_UNSUPPORTED(
                            "Unsupported type {}", mapTypeKindToName(typeKind));
                }
            },
            withCompanionFunctions,
            overwrite);
    }
} // namespace kumo::pollux::functions::aggregate::sparksql
